package org.jeecg.modules.demo.crm.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.demo.crm.entity.CWeixin;
import org.jeecg.modules.demo.crm.mapper.CWeixinMapper;
import org.jeecg.modules.demo.crm.service.ICWeixinService;
import org.jeecg.modules.demo.crm.util.DateUtils;
import org.jeecg.modules.demo.crm.util.wx.WxAvatar2MultipartFile;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.CompletableFuture;

/**
 * @Description: 微信记录表
 * @Author: jeecg-boot
 * @Date:   2025-07-15
 * @Version: V1.0
 */
@Service
public class CWeixinServiceImpl extends ServiceImpl<CWeixinMapper, CWeixin> implements ICWeixinService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private CWeixinMapper cWeixinMapper;

    @Autowired
    private RedisUtil redisUtil;
    @Override
    public JSONObject getWxLogin(JSONObject wxRes) {
        String openid = wxRes.getString("openid");
        CWeixin wxeixin = cWeixinMapper.findByOpenId(openid);
        if(wxeixin==null){
            return null;
        }else {
            SysUser sysUser = userMapper.selectById(wxeixin.getUserId());
            if(sysUser==null){
                return null;
            }
            JSONObject obj = new JSONObject();
            //5. 设置登录用户信息
            obj.put("userInfo", sysUser);

            //6. 生成token
            String token = JwtUtil.sign(sysUser.getUsername(),sysUser.getPassword());
            // 设置超时时间
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);

            obj.put("token", token);
            return obj;
        }

    }

    @Override
    public void wxBind(JSONObject wxRes) {
        String openid = wxRes.getString("openid");
        cWeixinMapper.deleteByOpenId(openid);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        cWeixinMapper.deleteByUserId(sysUser.getId());

        String userId = sysUser.getId();
        CWeixin cWeixin = new CWeixin();
        cWeixin.setUserId(userId);
        cWeixin.setOpenId(wxRes.getString("openid"));
        cWeixin.setNickName(wxRes.get("nickname")==null?null:wxRes.getString("nickname"));
        cWeixin.setSex(wxRes.get("sex")==null?null:wxRes.getString("sex"));
        cWeixin.setProvince(wxRes.get("province")==null?null:wxRes.getString("province"));
        cWeixin.setCity(wxRes.get("city")==null?null:wxRes.getString("city"));
        cWeixin.setCountry(wxRes.get("country")==null?null:wxRes.getString("country"));
        cWeixin.setHeadImgUrl(wxRes.get("headimgurl")==null?null:wxRes.getString("headimgurl"));
        cWeixin.setAvater(wxRes.get("headimgurl")==null?null:wxRes.getString("headimgurl"));
        cWeixin.setDataInfo(wxRes.toString());
        cWeixinMapper.insert(cWeixin);

        //异步将头像存入数据库
        CompletableFuture.runAsync(() -> {
            try {
                MultipartFile avatarFile = WxAvatar2MultipartFile.convert(cWeixin.getHeadImgUrl());
                // 3. 调你已有的 upload 方法
                String bizPath = "avatar/" + DateUtils.todayStr();
                String minioUrl = CommonUtils.upload(avatarFile, bizPath, "minio");
                CWeixin cWeixin1 = cWeixinMapper.selectById(cWeixin.getId());
                cWeixin1.setAvater(minioUrl);
                cWeixinMapper.updateById(cWeixin1);
            } catch (Exception e) {
                log.error("头像上传失败", e);
            }
        });




    }

    @Override
    public CWeixin findByUserId(String id) {
        return cWeixinMapper.findbyUserId(id);
    }

    @Override
    public void relieveWx() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        cWeixinMapper.deleteByUserId(sysUser.getId());
    }
}
